package com.cskaoyan.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.form.CartForm;
import com.cskaoyan.shopping.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author WuHuaguo
 * @since 2022/06/18 14:23
 */

@RestController
@RequestMapping("/shopping")
public class CartsController {

    @Autowired
    ICartService iCartService;

    @GetMapping("/carts")
    public ResponseData getCartListById(HttpServletRequest request) {
        String userInfo = request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());

        CartListByIdRequest cartListByIdRequest = new CartListByIdRequest();
        cartListByIdRequest.setUserId(uid);

        CartListByIdResponse response = iCartService.getCartListById(cartListByIdRequest);

        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getCartProductDtos());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @PostMapping("/carts")
    public ResponseData addToCart(@RequestBody CartForm cartForm) {
        AddCartRequest addCartRequest = new AddCartRequest();
        addCartRequest.setUserId(cartForm.getUserId());
        addCartRequest.setItemId(cartForm.getProductId());
        addCartRequest.setNum(cartForm.getProductNum());
        AddCartResponse response = iCartService.addToCart(addCartRequest);

        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getResult());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @PutMapping("/carts")
    public ResponseData UpdateCartNum(@RequestBody CartForm cartForm) {
        UpdateCartNumRequest updateCartNumRequest = new UpdateCartNumRequest();
        updateCartNumRequest.setUserId(cartForm.getUserId());
        updateCartNumRequest.setItemId(cartForm.getProductId());
        updateCartNumRequest.setChecked(cartForm.getChecked());
        updateCartNumRequest.setNum(cartForm.getProductNum());

        UpdateCartNumResponse response = iCartService.updateCartNum(updateCartNumRequest);

        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getResult());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }
}
